package com.hdl.school.service;

import static java.lang.Integer.parseInt;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.CardInfo;
import com.hdl.school.bean.DeviceLog;
import com.hdl.school.bean.StudentInfo;
import com.hdl.school.entity.NormalSerialCode;
import com.hdl.school.listener.OnCardEventListener;
import com.hdl.school.schoolcontroller.R;
import com.hdl.school.utils.BroadcastAction;
import com.hdl.school.utils.CRCUtil;
import com.hdl.school.utils.CardReaderManager;
import com.hdl.school.utils.Constants;
import com.hdl.school.utils.DeviceLogUtil;
import com.hdl.school.utils.HexUtil;
import com.hdl.school.utils.Logger;
import com.hdl.school.utils.StatusParser;
import com.hdl.school.utils.StringUtil;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.TaskManager;
import com.hdl.school.utils.TimeUtil;
import com.hdl.school.utils.USBSerialManager;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.likong.iotsdk.DeviceType;
import com.likong.iotsdk.IotServerCallback;
import com.likong.iotsdk.MyNetInfo;
import com.likong.iotsdk.RoomInfo;
import com.likong.iotsdk.ServerConnectionManager;
import com.tencent.bugly.crashreport.CrashReport;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


public class MqttService extends Service {
    private DbManager db;
    private String serviceIp = null;
    private String servicePort = null;
    private SharedPreferences sharedPreferences;
    private TaskManager taskManager;
    private static String mDevId = DeviceType.DEVICETYPE_CONTROLLER.toString();
    private List<Timer> queryTimerTask = new ArrayList<>();
    private JSONObject protocolObj;
    //当前设备状态的合集
    private JSONObject currentStatus = new JSONObject();
    private JSONArray sceneConfigs = new JSONArray();
    private MediaPlayer mediaPlayer = null;
    private boolean firstInit=true;

    /**
     * 服务器连接管理器
     */
    private ServerConnectionManager serverConnectionManager;

    private RoomInfo mRoomInfo;


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    int task = 0;
                    if (msg.obj != null) {
                        task = (int) msg.obj;
                    }
                    asyncCard(task);
                    break;
                case 1:
                    taskManager.reloadAllTask();
                    break;
                case 2:
                    RoomInfo roomInfo = (RoomInfo) msg.obj;
                    Intent intent = new Intent(BroadcastAction.ACTION_ROOMNAME);
                    intent.putExtra("room_name", roomInfo.getRoomName());
                    sendBroadcast(intent);
                    if(roomInfo.getSchoolName()!=null){
                        CrashReport.putUserData(MyApplication.myApplication, "school", roomInfo.getSchoolName());
                    }

                    break;
                case 6:
                    //中控升级固件
                    Intent intent1 = new Intent("com.leectrl.app.update");
                    intent1.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                    intent1.putExtra("mediaUrl", (String) msg.obj);
                    intent1.putExtra("installPackageName", "com.hdl.school.schoolcontroller");
                    sendBroadcast(intent1);
                    break;
                case 7:
                    //面板升级固件
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0A0000EEEC");
                    break;
                case 8:
                    //重启面板
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0C0000EEEC");
                    break;
                case 9:
                    //加载面板设置
                    loadBroadSetting();
                    break;
                case 10:
                    //退出面板APP
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE090000EEEC");
                    break;
                case 11:
                    //解锁面板
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee020100eeec");
                    break;
                case 12:
                    //锁定面板
                    checkBroadConfig();
                    break;
                case 13:
                    uploadZigbeeDeviceConfig();
                    break;
                case 19:
                    loadSceneConfigs();
                    break;
                case 21:
                    TCWManager.getInstance(MqttService.this).runRootCommand("setprop service.adb.tcp.port 5555");
                    TCWManager.getInstance(MqttService.this).execShell("stop adbd");
                    break;
                case 46:
                    Bus.getInstance().emit("scene_event",(String)msg.obj);
                    break;
                //liuyong 限制时间
                case 98:
                    mediaPlayer.reset();
                    try {
                        boolean success = (boolean) msg.obj;
                        Log.d("CardReaderManager", success ? "授权成功" : "授权失败");
                        if (!success) {
                            mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.limit));
                        }

                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case 99:
                    mediaPlayer.reset();
                    try {
                        boolean success = (boolean) msg.obj;
                        Log.d("CardReaderManager", success ? "授权成功" : "授权失败");
                        if (success) {
                            mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.success));
                        } else {
                            mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.failure));
                        }

                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case 100:
                    mediaPlayer.reset();
                    try {
                        int secend = (int) msg.obj;
                        switch (secend) {
                            case 1:
                                mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.busy_1));
                                break;
                            case 2:
                                mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.busy_2));
                                break;
                            case 3:
                                mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.busy_3));
                                break;
                            case 4:
                                mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.busy_4));
                                break;
                            case 5:
                                mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.busy_5));
                                break;
                        }
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case 997:
                    int index=1;
                    if(msg.obj!=null){
                        index= (int) msg.obj;
                    }
                    sendOffPCUDPBroadcast(index);
                    Message message2=new Message();
                    message2.what=998;
                    message2.obj=index;
                    handler.sendMessageDelayed(message2, 6000);
                    break;
                case 998:
                    sendOffPCUDPBroadcast((Integer) msg.obj);
                    break;
                case 999:
                    int index2=1;
                    if(msg.obj!=null){
                        index2= (int) msg.obj;
                    }
                    sendMagicPacket(index2);
                    Message message=new Message();
                    message.what=1000;
                    message.obj=index2;
                    handler.sendMessageDelayed(message, 4000);
                    break;
                case 1000:
                    sendMagicPacket((Integer) msg.obj);
                    break;
                case 10001:
                    //开大屏
                    String extraSerial=sharedPreferences.getString("c_setting_extraSerial",null);
                    if(extraSerial!=null) {
                        JSONObject extraSerialConfig = JSON.parseObject(extraSerial);
                        if (extraSerialConfig != null && extraSerialConfig.containsKey("enable") && extraSerialConfig.getBoolean("enable")) {
                            for (int i = 10001; i <=10008; i++) {
                                sendTCPMessage(i, extraSerialConfig.getString("power_on").replaceAll(" ",""));
                            }
                            Message newMsg=new Message();
                            newMsg.what=10003;
                            newMsg.obj=extraSerialConfig.getString("singal_hdmi").replaceAll(" ","");
                            handler.sendMessageDelayed(newMsg,30000);
                            Message newMsg2=new Message();
                            newMsg2.what=10003;
                            newMsg2.obj=extraSerialConfig.getString("singal_hdmi").replaceAll(" ","");
                            handler.sendMessageDelayed(newMsg2,60000);
                        }
                    }
                    break;
                case 10002:
                    //关大屏
                    String extraSerial2=sharedPreferences.getString("c_setting_extraSerial",null);
                    if(extraSerial2!=null) {
                        JSONObject extraSerialConfig = JSON.parseObject(extraSerial2);
                        if (extraSerialConfig != null && extraSerialConfig.containsKey("enable") && extraSerialConfig.getBoolean("enable")) {
                            for (int i = 10001; i <=10008; i++) {
                                sendTCPMessage(i, extraSerialConfig.getString("power_off").replaceAll(" ",""));
                            }
                        }
                    }
                    break;
                case 10003:
                    //切hdmi
                    for (int i = 10001; i <=10008; i++) {
                        sendTCPMessage(i, (String) msg.obj);
                    }
                    break;
                case 10007:
                    //指定端口切hdmi
                    sendTCPMessage(msg.arg1, (String) msg.obj);
                    break;
                case 10008:
                    //dzk 20231128 恢复面板下课状态
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceeea20000eeec");
                    break;
                case 10009:
                    //dzk 20240114 空调设置
                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", (String) msg.obj);
                    break;
                case 10010:

                    Bus.getInstance().emit("scene_event", "on_class");
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            db = x.getDb(((MyApplication) getApplicationContext()).getDaoConfig());
        } catch (DbException e) {
            e.printStackTrace();
        }
        sharedPreferences = getSharedPreferences("school_iot", 0);
        String deviceid = sharedPreferences.getString("c_setting_DEVICEID", null);
        if (deviceid == null) {
            deviceid = UUID.randomUUID().toString().replaceAll("-", "");
            sharedPreferences.edit().putString("c_setting_DEVICEID", deviceid).commit();
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });
        String deviceProtocolStr = sharedPreferences.getString("device_protocol", null);
        if (deviceProtocolStr != null) {
            try {
                JSONObject protocolConfigObj = JSON.parseObject(deviceProtocolStr);
                protocolObj = protocolConfigObj.getJSONObject("data");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            InputStream in = getResources().openRawResource(R.raw.protocol);
            int length = 0;
            try {
                length = in.available();
                byte [] buffer = new byte[length];
                in.read(buffer);
                String protocolStr=new String(buffer);
                protocolObj=JSON.parseObject(protocolStr);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String statusConfigStr = sharedPreferences.getString("statusConfig", null);
        if(statusConfigStr==null){
            InputStream in = getResources().openRawResource(R.raw.status);
            int length = 0;
            try {
                length = in.available();
                byte [] buffer = new byte[length];
                in.read(buffer);
                statusConfigStr=new String(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (statusConfigStr != null) {
            try {
                JSONObject statusConfigObj = JSON.parseObject(statusConfigStr);
                JSONObject statusObj = statusConfigObj.getJSONObject("data");
                setStatusQueryParams(statusObj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String serverConfig = sharedPreferences.getString("serverConfig", null);
        if (serverConfig != null) {
            String[] parts = serverConfig.split(":");
            if (parts.length == 2 && parts[0] != null && parts[1] != null) {
                loadDeviceProtocol(parts[0], parts[1]);
                loadStatusConfig(parts[0], parts[1]);
            }
        }
        taskManager = TaskManager.getInstance();
        taskManager.setContext(this);

        serverConnectionManager = ServerConnectionManager.getInstance(DeviceType.DEVICETYPE_CONTROLLER);
        serverConnectionManager.searchAndConnectSever(MqttService.this, new IotServerCallback() {
            @Override
            public void onSearchServerFailure() {

            }

            @Override
            public void onServerFound(String ip, String webPort, boolean isFoundFromLocal) {
                Log.e("MqttService", "搜索到服务器ip：" + ip + ",webPort:" + webPort);
                serviceIp = ip;
                servicePort = webPort;
                handler.sendEmptyMessage(0);
//                loadDeviceProtocol(serviceIp, servicePort);
//                loadStatusConfig(serviceIp, servicePort);
            }

            @Override
            public void onFailure(Throwable value) {
                Log.e("MqttService", "物联服务器连接错误");
            }


            @Override
            public void onServerConnected() {
                Log.e("MqttService", "物联服务器已连接");

                syncTime(serviceIp, servicePort);

                loadTelCtrlConfig(serviceIp, servicePort);
            }

            @Override
            public void onServerConnecteFailure() {
                Log.e("MqttService", "物联服务器连接失败");
            }

            @Override
            public void onServerDisconnected() {
                Log.e("MqttService", "物联服务器断开连接");
            }

            @Override
            public void onReceiveRoomInfo(RoomInfo roomInfo) {
                Message message = new Message();
                message.what = 2;
                message.obj = roomInfo;
                handler.sendMessage(message);
                mRoomInfo = roomInfo;
                sharedPreferences.edit().putString("room_info", JSON.toJSONString(roomInfo)).commit();
                //刷卡设置监听
                serverConnectionManager.subscribeTopic("/terminal/card/settings/change");
                //定时任务监听
                serverConnectionManager.subscribeTopic("/terminal/timer/task/change");
                //广播监听
                serverConnectionManager.subscribeTopic("/terminal/media/task/change");
                serverConnectionManager.subscribeTopic("/gatetway/" + roomInfo.getRoomId() + "/action/device/ctrl");
                serverConnectionManager.subscribeTopic("/ctrl/tx/room/" + roomInfo.getRoomId() + "/dev/controller");

                //dzk 20240114 共享空调设置
               // /terminal/broad/setting/change
                serverConnectionManager.subscribeTopic("/terminal/broad/setting/change");

                handler.sendEmptyMessage(1);
                //上报APP版本信息
                try {
                    PackageInfo packageInfo = MqttService.this.getPackageManager().
                            getPackageInfo(MqttService.this.getPackageName(), 0);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("action", "versioninfo");
                    JSONObject paramsObject = new JSONObject();
                    paramsObject.put("version_code", packageInfo.versionCode);
                    paramsObject.put("version_name", packageInfo.versionName);
                    jsonObject.put("params", paramsObject);
                    serverConnectionManager.publishMessage(JSON.toJSONString(jsonObject));
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                syncStudentInfo();
                loadScheduleInfo();
                loadSceneConfigs();
                uploadZigbeeDeviceConfig();
            }

            @Override
            public void onReceiveMessage(String topic, String message) {
                Log.e("MqttService", topic + "->" + message);
                if (topic.equals("/terminal/media/task/change")) {
                    handler.sendEmptyMessage(1);
                } else if (topic.equals("/terminal/timer/task/change")) {
                    syncStudentInfo();
                    loadScheduleInfo();
                }else if (topic.equals("/terminal/broad/setting/change")){//dzk 20240114
                    Log.d("dzkkt", "onReceiveMessage: 空调"+message);
                    JSONObject jsonObject = JSON.parseObject(message);
                    String action = jsonObject.getString("action");
                    Log.d("dzkkt", "onReceiveMessage: 空调"+action);
                    if ("shared_airctrl_broad_config".equals(action)){//空调设置
                        JSONObject sett= JSON.parseObject(jsonObject.getString("value"));
                        if (!sett.getBoolean("freeEnable")){
                            Message ms2=new Message();
                            ms2.obj="CEEE0E0200EEEC";
                            ms2.what=10009;
                            handler.sendMessage(ms2);
                            return;
                        }
                                // sett.getIntValue("lowTemp");
                        String lowTemp="01"+num2Hex(sett.getIntValue("lowTemp"),2);
                            String highTemp="01"+num2Hex(sett.getIntValue("highTemp"),2);
                            JSONArray addrArr=sett.getJSONArray("freeAddress");
                            String  addLen=num2Hex(addrArr.size(),2);
                            String addresses="";
                            for(int i=0;i<addrArr.size();i++){
                                //addresses.add(addrs.substring(i*2,(i+1)*2));
                                String a=num2Hex((String) addrArr.get(i),2);
                                addresses=addresses+a;
                            }
                        JSONArray freeDur=sett.getJSONArray("freeDur");
                           // String freeDurLen=num2Hex(freeDur.size(),2);
                        int freeDurLenInt=0;
                        String fd="";
                        for(int j=0;j<freeDur.size();j++){

                            if (((JSONObject)freeDur.get(j)).getBoolean("enable")){

                                freeDurLenInt++;
                                String startHour=num2Hex(((JSONObject)freeDur.get(j)).getDate("start_time").getHours(),2);
                                String startMin=num2Hex(((JSONObject)freeDur.get(j)).getDate("start_time").getMinutes(),2);
                                String endHour=num2Hex(((JSONObject)freeDur.get(j)).getDate("end_time").getHours(),2);
                                String endMin=num2Hex(((JSONObject)freeDur.get(j)).getDate("end_time").getMinutes(),2);
                                fd=fd+startHour+startMin+endHour+endMin;
                            }

                        }

                        String freeDurLen=num2Hex(freeDurLenInt,2);
                        String freeEnable="00";
                        if (sett.getBoolean("freeEnable")){
                            freeEnable="01";
                        }
                        String freeMode="00";
                        if ("timeDur".equals(sett.getString("freeMode"))){
                            freeMode="01";
                        }

                        String data="0000"+lowTemp+highTemp+addLen+addresses+freeDurLen+fd+freeEnable+freeMode;
                        String code="CEEE0E"+num2Hex(data.length(),2)+data+"EEEC";

                        Message ms=new Message();
                        ms.obj=code;
                        ms.what=10009;

                        Log.d("dzk", "onReceiveMessage:空调设置码： "+code);
                        handler.sendMessage(ms);
                    }
                } else if (topic.indexOf("/ctrl/tx/room/") == 0) {
                    JSONObject jsonObject = JSON.parseObject(message);
                    String action = jsonObject.getString("action");
                    if ("req_card".equals(action)) {
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = jsonObject.getIntValue("task_id");
                        handler.sendMessage(msg);
                    } else if ("ctrl".equals(action)) {
                        JSONArray devs = jsonObject.getJSONArray("devs");
                        long now = (new Date()).getTime();
                        for (int i = 0; i < devs.size(); i++) {
                            JSONObject dev = devs.getJSONObject(i);

                            Object unknowedDevId = dev.get("dev_id");
                            if (unknowedDevId instanceof Collection) {
                                JSONArray devIdArr = dev.getJSONArray("dev_id");
                                if (!devIdArr.contains(mDevId)) {
                                    continue;
                                }
                            } else {
                                String devId = dev.getString("dev_id");
                                if (!mDevId.equals(devId)) {
                                    continue;
                                }
                            }

                            JSONArray codes = dev.getJSONArray("codes");
                            if (codes.size() == 0) {
                                continue;
                            }
                            for (int j = 0; j < codes.size(); j++) {
                                //保存日志
                                JSONObject code = codes.getJSONObject(j);
                                DeviceLog deviceLog = new DeviceLog(2, 3, "设备控制：" + code.getString("name"), 0);
                                DeviceLogUtil.saveDeviceLog(deviceLog);

                                if(code.getString("name").contains("下课")||code.getString("name").contains("关系统")){

                                    handler.sendEmptyMessage(10008);
                                }
                                long sendTime = now;
                                if (code.containsKey("delay")) {
                                    sendTime = now + code.getLongValue("delay");
                                }
                                String hexCode = code.getString("code");
                                if (code.containsKey("portType")) {
                                    String subPortType = code.getString("portType");
                                    USBSerialManager.getInstence().sendCtrlSerialCode(subPortType, hexCode, sendTime);
                                } else if (dev.containsKey("portType")) {
                                    String portType = dev.getString("portType");
                                    USBSerialManager.getInstence().sendCtrlSerialCode(portType, hexCode, sendTime);
                                } else {
                                    USBSerialManager.getInstence().sendCtrlSerialCode(null, hexCode, sendTime);
                                }
                            }
                        }
                    } else if ("ctrl_zigbee".equals(action)) {
                        try {
                            genAndSendZigbeeCode(jsonObject.getJSONObject("params"), 0);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    } else if ("reboot".equals(action)) {

                        TCWManager.getInstance(MqttService.this).reboot();
                    } else if ("upgrade".equals(action)) {
                        if (jsonObject.containsKey("url")) {
                            String serverConfig = sharedPreferences.getString("serverConfig", null);
                            if (serverConfig != null) {
                                Message message1 = new Message();
                                message1.what = 6;
                                message1.obj = "http://" + serverConfig + jsonObject.getString("url");
                                handler.sendMessage(message1);
                            }
                        }

                    } else if ("upgradeBroad".equals(action)) {
                        if (jsonObject.containsKey("url")) {
                            String serverConfig = sharedPreferences.getString("serverConfig", null);
                            if (serverConfig != null) {
                                Message message1 = new Message();
                                message1.what = 7;
                                message1.obj = "http://" + serverConfig + jsonObject.getString("url");
                                handler.sendMessage(message1);
                            }
                        }
                    } else if ("rebootBroad".equals(action)) {
                        handler.sendEmptyMessage(8);
                    } else if ("broad_config_change".equals(action)) {
                        handler.sendEmptyMessage(9);
                    } else if ("scene_config_change".equals(action)) {
                        handler.sendEmptyMessage(19);
                    } else if ("exit_broad_app".equals(action)) {
                        handler.sendEmptyMessage(10);
                    } else if ("serial_debug".equals(action)) {
                        switchSerialDebug(jsonObject.getBooleanValue("value"));
                    } else if ("debug".equals(action)) {
                        openAdbDebug();
                    } else if ("unlock".equals(action)) {
                        handler.sendEmptyMessage(11);
                    } else if ("lock".equals(action)) {
                        handler.sendEmptyMessage(12);
                    } else if ("settings".equals(action)) {
                        String dev = jsonObject.getString("dev");
                        if (Constants.CONTROLLER_VERSION.toString().equals(dev)) {
                            JSONObject settings = jsonObject.getJSONObject("settings");
                            //设置BMT2000
                            JSONObject controllerSettings = settings.getJSONObject("controller");
                            String[] data = new String[]{controllerSettings.getString("shutdown_delay"), controllerSettings.getString("lockopen_time"), controllerSettings.getString("screen_delay"), controllerSettings.getString("init_volume"), controllerSettings.getString("booth_type"), controllerSettings.getString("init_output"), controllerSettings.getString("alert_time"), String.valueOf((controllerSettings.getBooleanValue("auto_close") ? '1' : '0')), String.valueOf((controllerSettings.getBooleanValue("auto_open") ? '1' : '0')), controllerSettings.getString("door_logic")};
                            String crcStr = num2Hex(Integer.parseInt((num2Hex(data[1].toString() + "0", 4)).substring(0, 2), 16) + Integer.parseInt((num2Hex(data[1].toString() + "0", 4)).substring(2, 4), 16) + Integer.parseInt((num2Hex(data[0].toString() + "0", 4)).substring(0, 2), 16) + Integer.parseInt((num2Hex(data[0].toString() + "0", 4)).substring(2, 4), 16) + Integer.parseInt((num2Hex(data[2].toString() + "0", 4)).substring(0, 2), 16) + Integer.parseInt((num2Hex(data[2].toString() + "0", 4)).substring(2, 4), 16) + Integer.parseInt((num2Hex(data[6].toString() + "0", 4)).substring(0, 2), 16) + Integer.parseInt((num2Hex(data[6].toString() + "0", 4)).substring(2, 4), 16) + Integer.parseInt((num2Hex(data[4], 2)), 16) + Integer.parseInt((num2Hex(data[3], 2)), 16) + Integer.parseInt((num2Hex(data[5], 2)), 16) + Integer.parseInt((num2Hex(data[7], 2)), 16) + Integer.parseInt((num2Hex(data[8], 2)), 16) + Integer.parseInt((num2Hex(data[9], 2)), 16) + 8 + 277, 2);
                            String content = num2Hex(data[1] + "0", 4) + num2Hex(data[0] + "0", 4) + num2Hex(data[2] + "0", 4) + num2Hex(data[4], 2) + num2Hex(data[3], 2) + num2Hex(data[5], 2) + "00010300010300" + num2Hex(data[6] + "0", 2) + "00" + num2Hex(data[8], 2) + num2Hex(data[7], 2) + num2Hex(data[9], 2) + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
                            String cmd = "fe0002d24100" + content + crcStr + "ff";
                            USBSerialManager.getInstence().sendStatusSerialCode(null, cmd, (new Date()).getTime() + 1000);
                            int[] indexs = new int[]{0, 1, 7, 8, 9, 15};
                            JSONObject casterSettings = settings.getJSONObject("caster");
                            for (int i = 0; i < 6; i++) {
                                if (!casterSettings.containsKey("p_" + i)) {
                                    continue;
                                }
                                String codeInPosition = casterSettings.getString("p_" + i).toLowerCase();
                                String mCmd = "fe000262310" + Integer.toHexString(indexs[i]) + StringUtil.padNum(codeInPosition.length() / 2, 2) + codeInPosition;
                                if (mCmd.length() < 108) {
                                    int padNumber = (108 - mCmd.length()) / 2;
                                    for (int j = 0; j < padNumber; j++) {
                                        mCmd += "00";
                                    }
                                }

                                mCmd += calTotalHex("0262310" + Integer.toHexString(indexs[i]) + StringUtil.padNum(codeInPosition.length() / 2, 2) + codeInPosition);
                                mCmd += "ff";
                                USBSerialManager.getInstence().sendStatusSerialCode(null, mCmd, (new Date()).getTime() + 1000);
                            }

                        }
                    } else if ("event".equals(action)) {
                        Message eventMsg=new Message();
                        eventMsg.what=46;
                        eventMsg.obj=jsonObject.getString("name");
                        handler.sendMessage(eventMsg);
                    } else if ("tmp_card_change".equals(action)) {

                    }
                    else if ("inClass".equals(action)) {
                        handler.sendEmptyMessage(10010);
                    }

                }
            }
        });
        CardReaderManager.getInstance().setOnCardEventListener(new OnCardEventListener() {
            @Override
            public void onCardPull(String cardNum) {

            }

            @Override
            public void onReceiveCard(String cardNum) {

            }

            @Override
            public void onCardCheckSuccess(String cardNum) {
                Message message = new Message();
                message.what = 99;
                message.obj = true;
                handler.sendMessage(message);
                USBSerialManager.getInstence().sendStatusSerialCode("cardreader", "FE010300EC56B23BEAFFFF");
                USBSerialManager.getInstence().setInClass(true);
                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0D010000EEEC");
            }

            @Override
            public void onCardCheckFailure(String cardNum) {
                Message message = new Message();
                message.what = 99;
                message.obj = false;
                handler.sendMessage(message);
                USBSerialManager.getInstence().sendStatusSerialCode("cardreader", "FE010300EC56B3FA2AFFFF");
                //USBSerialManager.getInstence().setInClass(false);
                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0D010001EEEC");
            }

            @Override
            public void onCardReaderBusy(int secends) {
                Message message = new Message();
                message.what = 100;
                message.obj = secends;
                handler.sendMessage(message);
                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0D0200030"+secends+"EEEC");
            }
            //liuyong 判断刷卡时间
            @Override
            public void onCardReaderLimit(String cardNum) {
                Message message = new Message();
                message.what = 98;
                message.obj = false;
                handler.sendMessage(message);
                //USBSerialManager.getInstence().sendStatusSerialCode("cardreader", "FE010300EC56B3FA2AFFFF");
                //USBSerialManager.getInstence().setInClass(false);
                //USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE0D010001EEEC");
            }
        });

        Bus.getInstance().on("screen_share", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
               JSONObject info=JSON.parseObject((String) message[0]);
                String extraSerial=sharedPreferences.getString("c_setting_extraSerial",null);
                if(extraSerial!=null) {
                    JSONObject extraSerialConfig = JSON.parseObject(extraSerial);
                    int from = info.getIntValue("from");
                    JSONArray to = info.getJSONArray("to");
                    //from的切回电脑，to的切到hdmi2
                    Message newMsg=new Message();
                    newMsg.what=10007;
                    newMsg.arg1=10000 + from;
                    if(from<7){
                        newMsg.obj=extraSerialConfig.getString("singal_pc").replaceAll(" ","");
                    }else{
                        newMsg.obj=extraSerialConfig.getString("singal_hdmi").replaceAll(" ","");
                    }

                    handler.sendMessageDelayed(newMsg,1000);
                    for (int m = 0; m < to.size(); m++) {
                        if(to.getIntValue(m)!=from){
                            Message newMsg2=new Message();
                            newMsg2.what=10007;
                            newMsg2.arg1=10000 + to.getIntValue(m);
                            newMsg2.obj=extraSerialConfig.getString("singal_hdmi").replaceAll(" ","");
                            handler.sendMessageDelayed(newMsg2,4000);
                            Message newMsg3=new Message();
                            newMsg3.what=10007;
                            newMsg3.arg1=10000 + to.getIntValue(m);
                            newMsg3.obj=extraSerialConfig.getString("singal_hdmi").replaceAll(" ","");
                            handler.sendMessageDelayed(newMsg3,7000);
                        }

                    }
                }
            }
        });
        Bus.getInstance().on("publish_feedback_msg", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                JSONObject obj = (JSONObject) message[0];
                Log.d("dzkpublish_feedback_msg", "onEvent: "+JSON.toJSONString(obj));
                serverConnectionManager.publishMessage(JSON.toJSONString(obj));
            }
        });
        Bus.getInstance().on("pull_card", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                checkBroadConfig();
            }
        });
        Bus.getInstance().on("scene_event", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                String eventName = (String) message[0];
                String ctrlEvent = eventName;
                if ("over_class".equals(eventName)) {
                    currentStatus.put("auth_status", 0);
                    handler.sendEmptyMessage(10002);
                    handler.sendEmptyMessage(10008);//dzk 20231129 下课回传状态
                    //liuyong 从下面拉上来
                    handler.removeMessages(999);
                    handler.removeMessages(1000);
                    handler.sendEmptyMessageDelayed(997,2000);
                } else if ("on_class".equals(eventName)) {
                    currentStatus.put("auth_status", 1);
                    handler.sendEmptyMessage(10001);
                    // //liuyong 从下面拉上来
                    handler.sendEmptyMessageDelayed(999,2000);
                    handler.removeMessages(997);
                }else if ("screen_off".equals(eventName)) {
                    handler.sendEmptyMessage(10002);
                }else if ("screen_on".equals(eventName)) {
                    handler.sendEmptyMessage(10001);
                } else if ("status_feedback".equals(eventName)) {
                    JSONObject json = (JSONObject) message[1];
                    if (json.containsKey("sensor_illuminance") || json.containsKey("sensor_temperature")) {
                        ctrlEvent = "sensor_data";
                        if (currentStatus.containsKey("sensor_data")) {
                            JSONObject sensorData = currentStatus.getJSONObject("sensor_data");
                            for (Map.Entry<String, Object> entry : json.entrySet()) {
                                sensorData.put(entry.getKey(), entry.getValue());
                            }
                            currentStatus.put("sensor_data", sensorData);
                        } else {
                            currentStatus.put("sensor_data", json);
                        }
                    }else if (json.containsKey("door_lock")){
                        String cStatus=json.getString("door_lock");
                        if("on".equals(cStatus)&&"off".equals(currentStatus.getString("door_lock"))){
                            ctrlEvent = "entrance_guard_open";
                        }else{
                            ctrlEvent=null;
                        }
                        currentStatus.put("door_lock", cStatus);
                    }
                } else if ("pull_card".equals(eventName)) {
                    long now = System.currentTimeMillis();
                    USBSerialManager.getInstence().clearCtrlSerialCode(null);
                    USBSerialManager.getInstence().setInClass(false);
                    String broadConfigStr = sharedPreferences.getString("broadConfig", null);
                    if (broadConfigStr == null || broadConfigStr.length() == 0) {
                        USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE030000EEEC");
                    } else {
                        JSONObject broadConfig = JSON.parseObject(broadConfigStr);
                        if (broadConfig.getBooleanValue("lock")) {
                            String openType = broadConfig.getString("openType");
                            if ("1".equals(openType)) {
                                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030100eeec");
                            } else if ("2".equals(openType)) {
                                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030200eeec");
                            //    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030200eeec", now + 500);
                            }
                        } else {
                            USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030000eeec");
                            USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030000eeec", now + 500);
                        }
                    }
                } else if ("slot_card".equals(eventName)) {
                    USBSerialManager.getInstence().clearCtrlSerialCode(null);
                }

                //执行情景模式
                if (protocolObj != null && protocolObj.containsKey("scene")) {
                    JSONObject scene = protocolObj.getJSONObject("scene");
                    if (scene.containsKey(eventName)) {
                        JSONObject sceneAction = scene.getJSONObject(eventName);
                        if (sceneAction.containsKey("enable") && sceneAction.getBooleanValue("enable") == false) {
                            return;
                        }
                        if (!sceneAction.containsKey("type")) {
                            return;
                        }
                        String sceneType = sceneAction.getString("type");
                        if (sceneType.equals("code")) {
                            JSONArray codes = sceneAction.getJSONArray("codes");
                            if (codes != null) {
                                long now = (new Date()).getTime();
                                for (int i = 0; i < codes.size(); i++) {
                                    JSONObject code = codes.getJSONObject(i);
                                    String portType = null;
                                    if (code.containsKey("portType")) {
                                        portType = code.getString("portType");

                                    } else if (sceneAction.containsKey("portType"))
                                        portType = sceneAction.getString("portType");

                                    if (code.containsKey("delay")) {
                                        USBSerialManager.getInstence().sendCtrlSerialCode(portType, code.getString("code"), now + code.getIntValue("delay"));
                                    } else {
                                        USBSerialManager.getInstence().sendCtrlSerialCode(portType, code.getString("code"));
                                    }
                                }
                            }
                        }
                    }

                }
               //liuyong 太冗余
               /* if ("on_class".equals(eventName)) {
                    handler.sendEmptyMessageDelayed(999, 2000);
                    handler.removeMessages(997);
                } else if ("over_class".equals(eventName)) {
                    handler.removeMessages(999);
                    handler.removeMessages(1000);
                    handler.sendEmptyMessage(997);
                }*/
                if(ctrlEvent==null){
                    return ;
                }
                if(sharedPreferences.contains("env_auto_ctrl")){
                    boolean autoCtrl = sharedPreferences.getBoolean("env_auto_ctrl", false);
                    if (autoCtrl) {
                        doSceneAutoCtrl(ctrlEvent);
                    }
                }else{
                    doSceneAutoCtrl(ctrlEvent);
                }
            }
        });
        Bus.getInstance().once("ctrl_zigbee", new Bus.MessageEvent() {

            @Override
            public void onEvent(String key, Object... message) {
                try {
                    genAndSendZigbeeCode((JSONObject) message[0], 5);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });
        Bus.getInstance().once("publish_zigbee_msg", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                JSONObject obj = (JSONObject) message[0];
                if (!obj.containsKey("action")) {
                    return;
                }
                String action = obj.getString("action");
                if (action.equals("ctrlzigbee")) {
                    //发送zigbee指令
                    String code = obj.getString("code").toUpperCase();
                    if (code.length() < 16) {
                        return;
                    }
                    String devTypeTag = code.substring(4, 6);
                    String actionTag = code.substring(6, 8);
                    String dataTag = code.substring(14, 16);
                    JSONObject jsonObject = new JSONObject();
                    JSONObject paramsObj = new JSONObject();
                    if (devTypeTag.equals("A0")) {
                        //控灯
                        if (actionTag.equals("F0")) {
                            if (dataTag.equals("01") || dataTag.equals("02")) {
                                //控单路灯
                                jsonObject.put("action", dataTag.equals("01") ? "open_light" : "close_light");
                                JSONArray jsonArray = new JSONArray();
                                jsonArray.add(parseInt(code.substring(8, 10), 16));
                                paramsObj.put("location", jsonArray);
                                jsonObject.put("paramsObj", paramsObj);
                                JSONArray devType = new JSONArray();
                                devType.add("zigbee-switcher");
                                devType.add("zigbee-switcher-t");
                                devType.add("zigbee-switcher-s");
                                jsonObject.put("devType", devType);
                                try {
                                    genAndSendZigbeeCode(jsonObject, 5);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            } else if (dataTag.equals("03") || dataTag.equals("04")) {
                                //控全部灯
                                int lineNum = parseInt(code.substring(8, 10), 16);
                                JSONArray lines = new JSONArray();
                                for (int i = 1; i <= lineNum; i++) {
                                    lines.add(i);
                                }
                                jsonObject.put("action", dataTag.equals("03") ? "open_light" : "close_light");
                                paramsObj.put("location", lines);
                                jsonObject.put("paramsObj", paramsObj);
                                JSONArray devType = new JSONArray();
                                devType.add("zigbee-switcher");
                                devType.add("zigbee-switcher-t");
                                devType.add("zigbee-switcher-s");
                                jsonObject.put("devType", devType);
                                try {
                                    genAndSendZigbeeCode(jsonObject, 5);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }

                        }

                    } else if (devTypeTag.equals("A1")) {
                        //控风扇

                    } else if (devTypeTag.equals("A3")) {
                        //控空调
                        if (actionTag.equals("F0")) {
                            //开关
                            if (dataTag.equals("26") || dataTag.equals("27")) {
                                action = (dataTag.equals("26") ? "open_airctrl_switcher" : "close_airctrl_switcher");
                            } else if (dataTag.equals("01") || dataTag.equals("02")) {
                                action = (dataTag.equals("01") ? "open_airctrl_power" : "close_airctrl_power");
                            }
                        } else if (actionTag.equals("F1")) {
                            //调温
                            action = "set_airctrl_temprature";
                            JSONArray temperatureArr = new JSONArray();
                            temperatureArr.add(Integer.parseInt(dataTag, 16));
                            paramsObj.put("temperature", temperatureArr);
                        } else if (actionTag.equals("F2")) {
                            //模式
                            action = "set_airctrl_mode";
                        } else if (actionTag.equals("F3")) {
                            //调速
                            action = "set_airctrl_speed";
                            JSONArray speedArray = new JSONArray();
                            speedArray.add(Integer.parseInt(dataTag, 16));
                            paramsObj.put("speed", speedArray);
                        }
                        if (action == null) {
                            return;
                        }
                        jsonObject.put("action", action);
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.add(Integer.parseInt(code.substring(8, 10), 16));
                        paramsObj.put("location", jsonArray);
                        jsonObject.put("paramsObj", paramsObj);
                        JSONArray devType = new JSONArray();
                        devType.add("zigbee-airctrl");
                        devType.add("airctrl-zigbee-leectrl");
                        jsonObject.put("devType", devType);
                        try {
                            genAndSendZigbeeCode(jsonObject, 5);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    } else if (devTypeTag.equals("A2")) {
                        String tag = null;
                        if (dataTag.equals("01") || dataTag.equals("03")) {
                            tag = "window_open";
                        } else if (dataTag.equals("02") || dataTag.equals("04")) {
                            tag = "window_close";
                        } else if (dataTag.equals("28")) {
                            tag = "stop_rotate";
                        }
                        if (tag == null) {
                            return;
                        }
                        jsonObject.put("action", tag);
                        JSONArray lines = new JSONArray();
                        if (dataTag.equals("01") || dataTag.equals("02") || dataTag.equals("28")) {
                            lines.add(Integer.parseInt(code.substring(8, 10), 16));
                        } else {
                            int lineNum = parseInt(code.substring(8, 10), 16);

                            for (int i = 1; i <= lineNum; i++) {
                                lines.add(i);
                            }
                        }

                        paramsObj.put("location", lines);
                        jsonObject.put("paramsObj", paramsObj);
                        JSONArray devType = new JSONArray();
                        devType.add("zigbee-curtain");
                        jsonObject.put("devType", devType);
                        try {
                            genAndSendZigbeeCode(jsonObject, 5);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        //执行指令
        Bus.getInstance().on("exec_action", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                //action, paramsObj, portType, sourceType
                String action = (String) message[0];
                JSONObject paramsObj = (JSONObject) message[1];
                String portType = (String) message[2];
                int sourceType = (int) message[3];
                if(action.equals("open_comp")){
                    Message message1=new Message();
                    message1.what=999;
                    message1.obj=paramsObj.getIntValue("location");
                    handler.sendMessage(message1);
                    if (sourceType > 0) {
                        DeviceLogUtil.saveDeviceLog(new DeviceLog(2, sourceType, "设备控制：开电脑", 0));
                    }
                }else if(action.equals("close_comp")){
                    Message message1=new Message();
                    message1.what=997;
                    message1.obj=paramsObj.getIntValue("location");
                    Bus.getInstance().emit("scene_event", "close_comp");
                    handler.sendMessage(message1);
                    if (sourceType > 0) {
                        DeviceLogUtil.saveDeviceLog(new DeviceLog(2, sourceType, "设备控制：关电脑",0));
                    }
                }else if (protocolObj != null && protocolObj.containsKey("actions")) {
                    JSONObject actions = protocolObj.getJSONObject("actions");
                    if (!actions.containsKey(action)) {
                        return;
                    }
                    JSONObject mAction = actions.getJSONObject(action);
                    if (mAction == null) {
                        return;
                    }
                    if (sourceType > 0) {
                        DeviceLogUtil.saveDeviceLog(new DeviceLog(2, sourceType, "设备控制：" + mAction.getString("name") + ",参数：" + JSON.toJSONString(paramsObj), 0));
                    }
                    if ("ZIGBEE".equals(portType) || "zigbee".equals(mAction.getString("protocol"))) {
                        JSONObject zigbeeParams = new JSONObject();
                        zigbeeParams.put("action", action);
                        if (paramsObj != null) {
                            zigbeeParams.put("paramsObj", paramsObj);
                        } else if (mAction.containsKey("paramsObj")) {
                            zigbeeParams.put("paramsObj", mAction.getJSONObject("paramsObj"));
                        }
                        if (mAction.containsKey("target_dev")) {
                            zigbeeParams.put("devType", mAction.getJSONArray("target_dev"));
                        }
                        try {
                            genAndSendZigbeeCode(zigbeeParams, 0);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }else if ("LORA".equals(portType) || "LORA".equals(mAction.getString("protocol"))) {
                        JSONObject object=new JSONObject();
                        object.put("action","ctrllora");
                        object.put("actionTag",action);
                        JSONObject params=new JSONObject();
                        params.put("type",2);
                        object.put("paramsObj",params);
                        serverConnectionManager.publishMessage(JSON.toJSONString(object));
                    } else {
                        //liuyong 下课联动关电脑
                        if(action.equals("over_class")){
                            Message message1=new Message();
                            message1.what=997;
                            message1.obj=paramsObj.getIntValue("location");
                            Bus.getInstance().emit("scene_event_liuyong", "close_comp");
                            handler.sendMessage(message1);
                            if (sourceType > 0) {
                                DeviceLogUtil.saveDeviceLog(new DeviceLog(2, sourceType, "设备控制：关电脑",0));
                            }
                        }
                        if ("code".equals(mAction.getString("type"))) {
                            JSONArray codes = mAction.getJSONArray("codes");
                            if (codes != null) {
                                long now = (new Date()).getTime();
                                for (int i = 0; i < codes.size(); i++) {
                                    JSONObject code = codes.getJSONObject(i);
                                    String mPortType=null;
                                    if (code.containsKey("portType")) {
                                        mPortType = code.getString("portType");

                                    } else if (mAction.containsKey("portType")) {
                                        mPortType = mAction.getString("portType");
                                    }
                                    if (code.containsKey("delay")) {
                                        USBSerialManager.getInstence().sendCtrlSerialCode(mPortType, code.getString("code"), now + code.getIntValue("delay"));
                                    } else {
                                        USBSerialManager.getInstence().sendCtrlSerialCode(mPortType, code.getString("code"));
                                    }
                                }
                            }
                        } else if ("script".equals(mAction.getString("type"))) {
                            if(mAction.containsKey("target_dev")&&mAction.containsKey("extraDev")){
                                JSONArray targets=mAction.getJSONArray("target_dev");
                                JSONObject extraDev=mAction.getJSONObject("extraDev");
                                if(targets!=null){
                                    for(int j=0;j<targets.size();j++){
                                       if((!targets.getString(j).contains("zigbee"))&&extraDev.containsKey(targets.getString(j))){
                                           JSONObject devParams=extraDev.getJSONObject(targets.getString(j));
                                           if(devParams!=null){
                                               if ("code".equals(devParams.getString("type"))) {
                                                   JSONArray codes = devParams.getJSONArray("codes");
                                                   if (codes != null) {
                                                       long now = (new Date()).getTime();
                                                       for (int i = 0; i < codes.size(); i++) {
                                                           JSONObject code = codes.getJSONObject(i);
                                                           if (code.containsKey("portType")) {
                                                               portType = code.getString("portType");

                                                           } else if (devParams.containsKey("portType")) {
                                                               portType = mAction.getString("portType");
                                                           }
                                                           if (code.containsKey("delay")) {
                                                               USBSerialManager.getInstence().sendCtrlSerialCode(portType, code.getString("code"), now + code.getIntValue("delay"));
                                                           } else {
                                                               USBSerialManager.getInstence().sendCtrlSerialCode(portType, code.getString("code"));
                                                           }
                                                       }
                                                   }
                                               } else if ("script".equals(devParams.getString("type"))) {
                                                   List<NormalSerialCode> codes = genCodesFromScript(devParams.getJSONArray("scripts"), paramsObj, devParams.getString("portType"));
                                                   if (codes != null && codes.size() > 0) {
                                                       long now = (new Date()).getTime();
                                                       for (NormalSerialCode code : codes) {
                                                           if (code.getPortType() != null) {
                                                               portType = code.getPortType();

                                                           } else if (mAction.containsKey("portType")) {
                                                               portType = mAction.getString("portType");
                                                           }
                                                           USBSerialManager.getInstence().sendCtrlSerialCode(portType, (String) code.getCode(), now + code.getDelay());
                                                       }
                                                   }
                                               }
                                           }
                                       }
                                    }
                                }
                            }else{
                                List<NormalSerialCode> codes = genCodesFromScript(mAction.getJSONArray("scripts"), paramsObj, mAction.getString("portType"));
                                if (codes != null && codes.size() > 0) {
                                    long now = (new Date()).getTime();
                                    for (NormalSerialCode code : codes) {
                                        if (code.getPortType() != null) {
                                            portType = code.getPortType();

                                        } else if (mAction.containsKey("portType")) {
                                            portType = mAction.getString("portType");
                                        }
                                        USBSerialManager.getInstence().sendCtrlSerialCode(portType, (String) code.getCode(), now + code.getDelay());
                                    }
                                }
                            }

                        }
                    }

                } else {
                    Log.e("MqttService", "未配置" + action + "协议");
                }
            }
        });
        Bus.getInstance().on("zigbee_dev_event", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                handler.sendEmptyMessage(13);
            }
        });
    }


    private void  sendTCPMessage(int port,String code){
        Intent intent=new Intent(Constants.ACTION_TCP_MESSAGE);
        intent.putExtra("code",code);
        intent.putExtra("port",port);
        sendBroadcast(intent);
    }


    private String calTotalHex(String mHex) {
        int total = 0;
        int len = mHex.length() / 2;
        for (int i = 0; i < len; i++) {
            total += parseInt(mHex.substring(i * 2, (i + 1) * 2), 16);
        }
        String totalHex = Integer.toHexString(total);
        return totalHex.substring(0, totalHex.length() - 2);
    }

    private String num2Hex(String num, int len) {
        String hex = Integer.toHexString(parseInt(num));
        int mLen = hex.length();
        if (mLen < len) {
            for (int j = 0; j < len - mLen; j++) {
                hex = "0" + hex;
            }
        }
        StringBuffer data = new StringBuffer();
        for (int i = hex.length() - 2; i >= 0; i = i - 2) {
            data.append(hex.substring(i, i + 2));
        }
        return data.toString();
    }

    private String num2Hex(int num, int len) {
        String hex = Integer.toHexString(num);
        int mLen = hex.length();
        if (mLen < len) {
            for (int j = 0; j < len - mLen; j++) {
                hex = "0" + hex;
            }
        }
        StringBuffer data = new StringBuffer();
        for (int i = hex.length() - 2; i >= 0; i = i - 2) {
            data.append(hex.substring(i, i + 2));
        }
        return data.toString();
    }


    private void switchSerialDebug(boolean enable) {
        USBSerialManager.getInstence().setDebugEnable(enable);
    }

    private void openAdbDebug() {
        TCWManager.getInstance(this).execShell("echo 0 > /sys/class/gpio_sw/PI5/data");
        handler.sendEmptyMessageDelayed(21, 3000);
    }

    public static boolean isProcessRunning(String processName) throws Exception {
        boolean running = false;
        Process process = null;
        process = Runtime.getRuntime().exec("ps");
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            if (line.contains(processName)) {
                running = true;
                break;
            }
        }
        in.close();
        process.waitFor();
        return running;
    }

    private void checkBroadConfig() {
        String broadConfigStr = sharedPreferences.getString("broadConfig", null);
        long now = System.currentTimeMillis();
        if (broadConfigStr == null || broadConfigStr.length() == 0) {
            USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE030000EEEC");
           // USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "CEEE030000EEEC", now + 500);
        } else {
            JSONObject broadConfig = JSON.parseObject(broadConfigStr);
            if (broadConfig.getBooleanValue("lock")) {
                String openType = broadConfig.getString("openType");
                    if ("1".equals(openType)) {
                        USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030100eeec");
                   //     USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030100eeec", now + 500);
                    } else if ("2".equals(openType)) {
                        USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030200eeec");
                     //   USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030200eeec", now + 500);
                    }

            } else {
                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030000eeec");
              //  USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030000eeec", now + 500);
            }
        }
    }

    private MyNetInfo getMyNetInfo() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (InterfaceAddress interfaceAddress : intf.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        return new MyNetInfo(interfaceAddress.getAddress().getHostAddress(), interfaceAddress.getBroadcast().toString().substring(1));
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private void sendMagicPacket(int index) {
        String macKey="computer_mac";
        if(index>1){
            macKey="computer_mac_"+index;
        }
        String mac = sharedPreferences.getString(macKey, null);
        if (TextUtils.isEmpty(mac)) {
            Toast.makeText(MqttService.this,"未获取到电脑的mac地址",Toast.LENGTH_SHORT).show();
            return;
        }
        mac = mac.replaceAll(":", "").replaceAll("-", "");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("FFFFFFFFFFFF");
        for (int i = 0; i < 16; i++) {
            stringBuffer.append(mac.toUpperCase());
        }
        //转换为2进制的魔术包数据
        final byte[] command = HexUtil.hexStr2BinArr(stringBuffer.toString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                //广播魔术包
                try {
                    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                    NetworkInterface networkInterface;
                    Enumeration<InetAddress> inetAddresses;
                    InetAddress inetAddress;
                    while (networkInterfaces.hasMoreElements()) {
                        networkInterface = networkInterfaces.nextElement();
                        inetAddresses = networkInterface.getInetAddresses();
                        while (inetAddresses.hasMoreElements()) {
                            inetAddress = inetAddresses.nextElement();
                            if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                                InetSocketAddress inetAddr = new InetSocketAddress(inetAddress, 58983);
                                //2.获取广播socket
                                DatagramSocket socket = new DatagramSocket(inetAddr);
                                socket.setBroadcast(true);

                                //3.封装数据包
                                /*public DatagramPacket(byte[] buf,int length
                                 *      ,InetAddress address
                                 *      ,int port)
                                 * buf：缓存的命令
                                 * length：每次发送的数据字节数，该值必须小于等于buf的大小
                                 * address：广播地址
                                 * port：广播端口
                                 */
                                DatagramPacket packet = new DatagramPacket(command, command.length, InetAddress.getByName("255.255.255.255"), 3000);
                                //4.发送数据
                                socket.send(packet);
                                //5.关闭socket
                                socket.close();
                            }
                        }
                    }
                } catch (UnknownHostException e) {
                    //Ip地址错误时候抛出的异常
                    e.printStackTrace();
                } catch (IOException e) {
                    //获取socket失败时候抛出的异常
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void sendOffPCUDPBroadcast(int index){
        String macKey="computer_mac";
        if(index>1){
            macKey="computer_mac_"+index;
        }
        String mac = sharedPreferences.getString(macKey, null);
        if (TextUtils.isEmpty(mac)) {
            return;
        }
        mac = mac.replaceAll(":", "").replaceAll("-", "");
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("action","shutdown_pc");
        jsonObject.put("target",mac);
        final byte[] command=JSON.toJSONString(jsonObject).getBytes();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //广播魔术包
                try {
                    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                    NetworkInterface networkInterface;
                    Enumeration<InetAddress> inetAddresses;
                    InetAddress inetAddress;
                    while (networkInterfaces.hasMoreElements()) {
                        networkInterface = networkInterfaces.nextElement();
                        inetAddresses = networkInterface.getInetAddresses();
                        while (inetAddresses.hasMoreElements()) {
                            inetAddress = inetAddresses.nextElement();
                            if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                                InetSocketAddress inetAddr = new InetSocketAddress(inetAddress, 0);
                                //2.获取广播socket
                                DatagramSocket socket = new DatagramSocket(inetAddr);


                                socket.setBroadcast(true);
                                DatagramPacket packet = new DatagramPacket(command, command.length, InetAddress.getByName("255.255.255.255"), 12357);
                                //4.发送数据
                                socket.send(packet);
                                //5.关闭socket
                                socket.close();
                            }
                        }
                    }
                } catch (UnknownHostException e) {
                    //Ip地址错误时候抛出的异常
                    e.printStackTrace();
                } catch (IOException e) {
                    //获取socket失败时候抛出的异常
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 生成并发送zigbee指令
     *
     * @param obj
     * @param sourceType 1远程控制  5面板
     */
    private void genAndSendZigbeeCode(JSONObject obj, int sourceType) throws DbException {
        if (obj == null) {
            return;
        }
        if (protocolObj == null || (!protocolObj.containsKey("actions"))) {
            return;
        }
        JSONObject actions = protocolObj.getJSONObject("actions");
        JSONObject actionOfTag = actions.getJSONObject(obj.getString("action"));
        if (actionOfTag == null) {
            Logger.e("未找到对应控制协议");
            return;
        }

        JSONObject paramsObj = obj.getJSONObject("paramsObj");
        if (paramsObj == null) {
            return;
        }
        if (sourceType > 0) {
            DeviceLogUtil.saveDeviceLog(new DeviceLog(2, sourceType, "设备控制：" + actionOfTag.getString("name") + ",参数：" + JSON.toJSONString(paramsObj), 0));
        }

        if (!obj.containsKey("devType")) {
            if (actionOfTag.containsKey("target_dev")) {
                obj.put("devType", actionOfTag.getJSONArray("target_dev"));
            }
        }
        if (!obj.containsKey("devType")) {
            return;
        }
        JSONArray devType = obj.getJSONArray("devType");
        if (devType.size() == 0) {
            return;
        }
        List<ZigbeeDevice> roomZigbeeDevices = DbUtil.getInstance().selector(ZigbeeDevice.class).where("device_type", "in", devType).findAll();
        if (roomZigbeeDevices == null || roomZigbeeDevices.size() == 0) {
            return;
        }
        //要控制的目标线路
        JSONArray targetLines = paramsObj.getJSONArray("location");
        //遍历设备，找到指定线路
        for (ZigbeeDevice roomZigbeeDevice : roomZigbeeDevices) {
            String[] lines = roomZigbeeDevice.getDevicekey().split(",");
            //转换线路下标 0开始
            List<Integer> indexArr = new ArrayList<>();
            List<Integer> keys = new ArrayList<>();
            for (int i = 0; i < targetLines.size(); i++) {
                for (int j = 0; j < lines.length; j++) {
                    if (String.valueOf(targetLines.getIntValue(i)).equals(lines[j])) {
                        indexArr.add(j);
                        if(!keys.contains(targetLines.getIntValue(i))){
                            keys.add(targetLines.getIntValue(i));
                        }
                    }
                }
            }
            //绑定的线路中必须包含目标线路中的某一路
            if (indexArr.size() == 0) {
                continue;
            }

            paramsObj.put("dev_id", roomZigbeeDevice.getDeviceType());
            paramsObj.put("targetIndexs", indexArr);
            paramsObj.put("keys", keys);
            String mac = roomZigbeeDevice.getMac();
            if (mac != null) {
                if (actionOfTag.containsKey("extraDev")) {
                    //附加设备，加载附加设备协议
                    JSONObject extraDev = actionOfTag.getJSONObject("extraDev");
                    if ((extraDev == null) || (!extraDev.containsKey(roomZigbeeDevice.getDeviceType()))) {
                        continue;
                    }
                    JSONObject extraAction = extraDev.getJSONObject(roomZigbeeDevice.getDeviceType());
                    execZigbeeAction(extraAction, mac, paramsObj);
                } else {
                    //自身控制，加载自身协议
                    execZigbeeAction(actionOfTag, mac, paramsObj);
                }
            }

        }
    }

    private void execZigbeeAction(JSONObject actionConfig, final String mac, JSONObject paramsObj) {
        String actionType = actionConfig.getString("type");
        if ("script".equals(actionType)) {
            List<NormalSerialCode> codes = genCodesFromScript(actionConfig.getJSONArray("scripts"), paramsObj, null);
            if (codes != null && codes.size() > 0) {
                for (NormalSerialCode c : codes) {
                    Bus.getInstance().emit("zigbee_code", mac, c);
                }
            }
        }

    }

    private List<NormalSerialCode> genCodesFromScript(JSONArray scripts, JSONObject paramsObj, String portType) {
        if ((scripts == null) || scripts.size() == 0 || (paramsObj == null)) {
            Logger.e("脚本参数错误");
            return null;
        }
        List<NormalSerialCode> normalSerialCodes = new ArrayList<>();
        for (int i = 0; i < scripts.size(); i++) {
            JSONObject mScript = scripts.getJSONObject(i);
            String scriptSource = mScript.getString("script");
            String name = mScript.getString("name");
            int delay = 0;
            if (mScript.containsKey("delay")) {
                delay = mScript.getIntValue("delay");
            }
            String scriptStr = "var params=" + JSON.toJSONString(paramsObj) + ";RESULT=(function(params){" + scriptSource + "})(params)";
            try {
                CRCUtil crcUtil = new CRCUtil();
                V8 runtime = V8.createV8Runtime();
                V8Object v8CRC = new V8Object(runtime);
                runtime.add("crc", v8CRC);
                v8CRC.registerJavaMethod(crcUtil, "ToModbusCRC16", "ToModbusCRC16", new Class<?>[]{String.class});
                V8Object parsedObj = runtime.executeObjectScript(scriptStr);
                V8Object json = runtime.getObject("JSON");
                V8Array args = new V8Array(runtime).push(parsedObj);
                String result = (String) json.executeFunction("stringify", args);
                args.release();
                json.release();
                v8CRC.release();
                parsedObj.release();
                runtime.release();
                List<Object> mCodes = JSON.parseArray(result, Object.class);

                if (mCodes == null) {
                    Logger.e("脚本错误或没有return");
                } else {
                    if (mCodes.size() > 0) {
                        for (Object mc : mCodes) {
                            NormalSerialCode normalSerialCode = new NormalSerialCode();
                            normalSerialCode.setName(name);
                            normalSerialCode.setDelay(delay);
                            normalSerialCode.setCode(mc);
                            if (portType != null) {
                                normalSerialCode.setPortType(portType);
                            }
                            normalSerialCodes.add(normalSerialCode);
                        }
                    }
                }
            } catch (Exception e) {
                Logger.e(scriptStr + "脚本错误:" + e.getMessage());
                return null;
            }
        }
        return normalSerialCodes;
    }

    private void loadSceneConfigs() {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + servicePort + "/publicapi/iscn/scene/event/setting/load");
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("room", mRoomInfo.getRoomId());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        JSONObject res = JSON.parseObject(result);
                        if (res.getIntValue("code") == 0) {
                            JSONArray jsonArray = new JSONArray();
                            JSONArray configs = res.getJSONArray("data");
                            long now = (new Date()).getTime();
                            for (int i = 0; i < configs.size(); i++) {
                                JSONObject item = configs.getJSONObject(i);
                                String startDate = item.getString("start_date");
                                String endDate = item.getString("end_date");
                                if (TimeUtil.string2Date(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime() <= now && TimeUtil.string2Date(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss").getTime() > now) {
                                    jsonArray.add(item);
                                }
                            }
                            sceneConfigs = jsonArray;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("MqttService", ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void doSceneAutoCtrl(String eventName) {
        long now = (new Date()).getTime();
        for (int i = 0; i < sceneConfigs.size(); i++) {
            JSONObject item = sceneConfigs.getJSONObject(i);
            if (!eventName.equals(item.getString("event_type"))) {
                continue;
            }
            boolean inTime = false;
            JSONArray times = item.getJSONArray("times");
            if (times == null) {
                continue;
            }
            for (int j = 0; j < times.size(); j++) {
                JSONObject timeObj = times.getJSONObject(j);
                String startTime = timeObj.getString("start_time");
                String endTime = timeObj.getString("end_time");
                if (TimeUtil.timeInToday(startTime) <= now && TimeUtil.timeInToday(endTime) > now) {
                    inTime = true;
                    break;
                }
            }
            if (!inTime) {
                continue;
            }
            StringBuffer conditionBuffer = new StringBuffer();
            JSONArray conditions = item.getJSONArray("condition_params");
            for (int j = 0; j < conditions.size(); j++) {
                JSONObject condition = conditions.getJSONObject(j);
                String key = condition.getString("key");
                if(!("none".equals(key))){
                    if (condition.containsKey("conditionTag")) {
                        if (condition.containsKey("numberOptionKey")) {
                            conditionBuffer.append("&&currentStatus[\"" + key + "\"][\"" + condition.getString("numberOptionKey") + "\"]!==undefined&&currentStatus[\"" + key + "\"][\"" + condition.getString("numberOptionKey") + "\"]" + condition.getString("conditionTag") + condition.getString("conditionValue"));
                        } else {
                            conditionBuffer.append("&&currentStatus[\"" + key + "\"]" + condition.getString("conditionTag") + condition.getString("conditionValue"));
                        }
                    } else {
                        conditionBuffer.append("&&currentStatus[\"" + key + "\"]" + "===" + condition.getString("conditionValue"));
                    }
                }
            }
            if (conditionBuffer.length() > 0) {
                String conditionString = "var currentStatus=" + JSON.toJSONString(currentStatus) + ";var checkValue=" + conditionBuffer.substring(2).toString() + ";var result=false;if(checkValue){result=true;}result;";
                Log.e("conditionString", conditionString);
                V8 runtime = V8.createV8Runtime();
                boolean parsedResult = runtime.executeBooleanScript(conditionString);
                runtime.release();
                if (parsedResult) {
                    JSONArray actions = item.getJSONArray("actions");
                    if (actions != null && actions.size() > 0) {
                        for (int k = 0; k < actions.size(); k++) {
                            JSONObject action = actions.getJSONObject(k);
                            String protocol=null;
                            if(action.containsKey("protocol")){
                                protocol=action.getString("protocol");
                            }
                            if (action.containsKey("location")) {
                                JSONObject paramsObj = new JSONObject();
                                paramsObj.put("location", action.getJSONArray("location"));
                                Bus.getInstance().emit("exec_action", action.getString("action"), paramsObj, protocol, 4);
                            } else {
                                Bus.getInstance().emit("exec_action", action.getString("action"), null, protocol, 4);
                            }

                        }
                    }
                }
            }else{
                JSONArray actions = item.getJSONArray("actions");
                if (actions != null && actions.size() > 0) {
                    for (int k = 0; k < actions.size(); k++) {
                        JSONObject action = actions.getJSONObject(k);
                        String protocol=null;
                        if(action.containsKey("protocol")){
                            protocol=action.getString("protocol");
                        }
                        if (action.containsKey("location")) {
                            JSONObject paramsObj = new JSONObject();
                            paramsObj.put("location", action.getJSONArray("location"));
                            Bus.getInstance().emit("exec_action", action.getString("action"), paramsObj, protocol, 4);
                        } else {
                            Bus.getInstance().emit("exec_action", action.getString("action"), null, protocol, 4);
                        }

                    }
                }
            }
        }
    }

    private void loadDeviceProtocol(String serviceIp, String webPort) {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + webPort + "/publicapi/terminal/protocol/load");
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("deviceId", DeviceType.DEVICETYPE_CONTROLLER.toString());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        JSONObject protocolConfigObj = JSON.parseObject(result);
                        sharedPreferences.edit().putString("device_protocol", result).commit();
                        protocolObj = protocolConfigObj.getJSONObject("data");
                    } catch (Exception e) {

                    }

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("MqttService", ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void loadBroadSetting() {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + servicePort + "/publicapi/system/broad/setting/load");
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("room", mRoomInfo.getRoomId());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        JSONObject resObj = JSON.parseObject(result);
                        if (resObj.getIntValue("code") == 0) {
                            JSONObject data = resObj.getJSONObject("data");
                            String broadConfigStr = JSON.toJSONString(data);
                            sharedPreferences.edit().putString("broadConfig", broadConfigStr).commit();
                            if (data.getBooleanValue("lock")) {
                                String openType = data.getString("openType");
                                if ("1".equals(openType)) {
                                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030100eeec");
                                } else if ("2".equals(openType)) {
                                    USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030200eeec");
                                }
                            } else {
                                USBSerialManager.getInstence().sendCtrlSerialCode("controlpanel", "ceee030000eeec");
                            }

                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("MqttService", ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 同步并调整系统时间
     *
     * @param serviceIp
     * @param webPort
     */
    private void syncTime(String serviceIp, String webPort) {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + webPort + "/publicapi/terminal/sys/getTime");
        requestParams.setAsJsonContent(true);
        setCommonHeader(requestParams);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result==null){
                    return ;
                }
                try {
                    JSONObject timeObj = JSON.parseObject(result);
                    if (timeObj.getIntValue("code") == 0) {
                        long time = timeObj.getLongValue("data");
                        Date date = new Date(time);
                        TCWManager.getInstance(MyApplication.myApplication).setTime(1900 + date.getYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void loadTelCtrlConfig(String serviceIp, String webPort) {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + webPort + "/publicapi/tool/telctrl/unit/info/load");
        setCommonHeader(requestParams);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result==null){
                    return ;
                }
                try {
                    JSONObject unitObj = JSON.parseObject(result);
                    if (unitObj.getIntValue("code") == 0) {
                        sharedPreferences.edit().putInt("ctrl_unit", unitObj.getIntValue("data")).commit();
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void loadStatusConfig(String serviceIp, String webPort) {
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + webPort + "/publicapi/terminal/status/config");
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("deviceId", DeviceType.DEVICETYPE_CONTROLLER.toString());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        JSONObject statusConfigObj = JSON.parseObject(result);
                        sharedPreferences.edit().putString("statusConfig", result).commit();

                        JSONObject statusObj = statusConfigObj.getJSONObject("data");
                        setStatusQueryParams(statusObj);
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void loadScheduleInfo() {
        if (mRoomInfo == null) {
            return;
        }
        RequestParams requestParams = new RequestParams();
        requestParams.setUri("http://" + serviceIp + ":" + servicePort + "/deviceapi/terminal/room/schedule/load");
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("room", mRoomInfo.getRoomId());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        JSONObject resultObj = JSON.parseObject(result);
                        JSONObject scheduleData = resultObj.getJSONObject("data");
                        sharedPreferences.edit().putString("roomSchedule", JSON.toJSONString(scheduleData)).commit();
                        CardReaderManager.getInstance().setScheduleData(scheduleData);
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    private void setStatusQueryParams(JSONObject jsonObject) {
        JSONArray parserParams = jsonObject.getJSONArray("parserParams");
        if (parserParams.size() > 0) {
            List<JSONObject> pp = new ArrayList<>();
            for (int i = 0; i < parserParams.size(); i++) {
                JSONObject parser = parserParams.getJSONObject(i);
                if (mDevId.equals(parser.getString("dev_id"))) {
                    JSONArray parserArr = parser.getJSONArray("params");
                    for (int k = 0; k < parserArr.size(); k++) {
                        pp.add(parserArr.getJSONObject(k));
                    }

                }
            }
            if (pp.size() > 0) {
                StatusParser.getInstance().setStatusParserScripts(pp);
            }
        }

        JSONArray queryParams = jsonObject.getJSONArray("queryParams");
        for (Timer timer : queryTimerTask) {
            if (timer != null) {
                timer.cancel();
            }
        }
        queryTimerTask.clear();
        if (queryParams.size() > 0) {
            for (int i = 0; i < queryParams.size(); i++) {
                JSONObject q = queryParams.getJSONObject(i);
                if (mDevId.equals(q.getString("dev_id")) && ((!q.containsKey("enable")) || q.getBooleanValue("enable"))) {
                    final JSONArray params = q.getJSONArray("params");
                    String mTarget = null;
                    if (q.containsKey("target")) {
                        mTarget = q.getString("target");
                    }
                    final String target = mTarget;
                    if (params != null && params.size() > 0 && q.containsKey("duration")) {
                        Timer timer = new Timer();
                        timer.scheduleAtFixedRate(new TimerTask() {
                            @Override
                            public void run() {
                                //liuyong 增加try catch
                                try {
                                    exeQueryParams(params, target);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, 8000, q.getIntValue("duration"));
                        queryTimerTask.add(timer);
                    }
                }
            }
        }
    }

    /**
     * 执行查询
     *
     * @param params 查询参数
     * @param target 查询端口
     */
    private void exeQueryParams(JSONArray params, String target) {
        for (int i = 0; i < params.size(); i++) {
            JSONObject p = params.getJSONObject(i);
            if (p.containsKey("enable") && (!p.getBooleanValue("enable"))) {
                continue;
            }
            int delay = 0;
            if (p.containsKey("delay") && p.getIntValue("delay") > 0) {
                delay = p.getIntValue("delay");
            }
            if (p.containsKey("key")) {
                USBSerialManager.getInstence().sendStatusSerialCode(target, p.getString("code"), System.currentTimeMillis() + delay, p.getString("key"));
            } else {
                USBSerialManager.getInstence().sendStatusSerialCode(target, p.getString("code"), System.currentTimeMillis() + delay);
            }

        }
    }

    private void setCommonHeader(RequestParams requestParams, String body) {
        long time = System.currentTimeMillis();
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        String cryptonym = sb.toString();
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            String url = requestParams.getUri();
            String signStr = url + "&@" + time + "&@" + cryptonym;
            if (body != null) {
                signStr += body;
            }
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(signStr.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            requestParams.addHeader("requestTime", time + "");
            requestParams.addHeader("url", url);
            requestParams.addHeader("cryptonym", cryptonym);
            requestParams.addHeader("sign", new String(buf));
        } catch (Exception e) {

        }
    }

    private void setCommonHeader(RequestParams requestParams) {
        setCommonHeader(requestParams, null);
    }

    private void uploadZigbeeDeviceConfig() {
        try {
            JSONObject zigbeeDeviceInfo = new JSONObject();
            List<ZigbeeDevice> zigbeeDevices = DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
            if (zigbeeDevices != null) {
                for (ZigbeeDevice zigbeeDevice : zigbeeDevices) {
                    JSONArray params = new JSONArray();
                    if (zigbeeDeviceInfo.containsKey(zigbeeDevice.getDeviceType())) {
                        params = zigbeeDeviceInfo.getJSONArray(zigbeeDevice.getDeviceType());
                    }

                    String[] devKeys = zigbeeDevice.getDevicekey().split(",");
                    String[] names = zigbeeDevice.getDeviceName().split(",");
                    for (int i = 0; i < devKeys.length; i++) {
                        JSONObject line = new JSONObject();
                        line.put("value", devKeys[i]);
                        line.put("title", names[i]);
                        params.add(line);
                    }

                    zigbeeDeviceInfo.put(zigbeeDevice.getDeviceType(), params);
                }
            }
            if (serviceIp == null || servicePort == null|| mRoomInfo==null) {
                return;
            }
            RequestParams requestParams = new RequestParams(String.format("http://%s:%s/publicapi/terminal/zigbee/config/upload", serviceIp, servicePort));
            requestParams.setMaxRetryCount(30);
            requestParams.setAsJsonContent(true);
            JSONObject body = new JSONObject();
            body.put("room", mRoomInfo.getRoomId());
            body.put("zigbeeDeviceInfo", zigbeeDeviceInfo);
            requestParams.setBodyContent(JSON.toJSONString(body));
            setCommonHeader(requestParams);
            x.http().post(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("MqttService", result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    private void syncStudentInfo() {
        if (mRoomInfo == null) {
            return;
        }
        RequestParams requestParams = new RequestParams(String.format("http://%s:%s/deviceapi/terminal/student/all/load", serviceIp, servicePort));
        requestParams.setMaxRetryCount(30);
        requestParams.setAsJsonContent(true);
        JSONObject body = new JSONObject();
        body.put("roomId", mRoomInfo.getRoomId());
        requestParams.setBodyContent(JSON.toJSONString(body));
        setCommonHeader(requestParams, JSON.toJSONString(body));
        x.http().post(requestParams, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(final String result) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            if (jsonObject.getInteger("code") == 0) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                final List<StudentInfo> studentInfos = new ArrayList<>();
                                for (int j = 0; j < data.size(); j++) {
                                    JSONObject card = data.getJSONObject(j);
                                    StudentInfo studentInfo = new StudentInfo();
                                    studentInfo.setStudentId(card.getIntValue("id"));
                                    studentInfo.setCardNum(card.getString("card_num"));
                                    studentInfo.setDepartment(card.getString("department"));
                                    studentInfo.setClassId(card.getIntValue("class_id"));
                                    studentInfo.setName(card.getString("name"));
                                    studentInfo.setClassName(card.getString("class_name"));
                                    studentInfos.add(studentInfo);
                                }
                                saveStudentInfo(studentInfos);
                            }
                        } catch (Exception e) {

                        }
                    }
                }).start();

            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void asyncCard(final int id) {
        RequestParams requestParams = new RequestParams(String.format("http://%s:3009/deviceapi/terminal/card/all/load", serviceIp));
        requestParams.setMaxRetryCount(Integer.MAX_VALUE);
        setCommonHeader(requestParams);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(final String result) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            if (jsonObject.getInteger("code") == 0) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                final List<CardInfo> cardInfos = new ArrayList<CardInfo>();
                                for (int j = 0; j < data.size(); j++) {
                                    JSONObject card = data.getJSONObject(j);
                                    CardInfo cardInfo = new CardInfo();
                                    cardInfo.setCardNum(card.getString("card_num"));
                                    cardInfo.setDepartment(card.getString("department"));
                                    cardInfo.setPosition(card.getString("position"));
                                    cardInfo.setName(card.getString("name"));
                                    cardInfo.setSex(card.getIntValue("sex"));
                                    cardInfo.setCardType(card.getIntValue("card_type"));
                                    cardInfo.setCreateTime(card.getDate("add_time"));
                                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        cardInfo.setStartTime(formatter.parse(card.getString("start_time")));
                                        cardInfo.setEndTime(formatter.parse(card.getString("end_time")));
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    cardInfos.add(cardInfo);
                                }
                                boolean res = saveCardInfo(cardInfos);
                                if (res && id > 0) {
                                    JSONObject object = new JSONObject();
                                    object.put("action", "finish_sync_card");
                                    object.put("task_id", id);
                                    serverConnectionManager.publishMessage(JSON.toJSONString(object));
                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                }).start();

            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private boolean saveStudentInfo(List<StudentInfo> studentInfos) {
        if (db == null) {
            return false;
        }
        if (studentInfos == null) {
            return false;
        }
        try {
            //获取本地卡库
            List<StudentInfo> students = db.findAll(StudentInfo.class);
            if (studentInfos.size() == 0) {
                //清空卡库
                if (students != null && students.size() > 0) {
                    db.execNonQuery("update student_info set delete_tag=1");
                }
            } else {
                if (students == null || students.size() == 0) {
                    //本地没有卡信息，全部保存
                    for (int j = 0; j < studentInfos.size(); j++) {
                        db.save(studentInfos.get(j));
                    }
                } else {
                    int index = 0;
                    //比较卡库
                    for (StudentInfo studentInfo : studentInfos) {
                        boolean exsit = false;
                        for (StudentInfo mStudent : students) {
                            if (mStudent.getCardNum().equals(studentInfo.getCardNum())) {
                                studentInfo.setId(mStudent.getId());
                                exsit = true;
                                break;
                            }
                        }
                        if (exsit) {
                            //存在相同卡，更新信息
                            studentInfo.setDeleteTag(0);
                            db.saveOrUpdate(studentInfo);
                        } else {
                            db.save(studentInfo);
                        }
                    }
                    for (StudentInfo mStudent : students) {
                        boolean exsit = false;
                        for (StudentInfo studentInfo : studentInfos) {
                            if (mStudent.getCardNum().equals(studentInfo.getCardNum())) {
                                exsit = true;
                                break;
                            }
                        }
                        if (!exsit) {
                            //本地的卡号被删除
                            db.execNonQuery("update student_info set  delete_tag=1 where id=" + mStudent.getId());
                        }
                        index++;
                    }
                }
            }
            return true;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 保存卡信息
     */
    private boolean saveCardInfo(List<CardInfo> cardInfos) {
        if (db == null) {
            return false;
        }
        if (cardInfos == null) {
            return false;
        }
        try {
            //获取本地卡库
            List<CardInfo> cards = db.findAll(CardInfo.class);
            if (cardInfos.size() == 0) {
                //清空卡库
                if (cards != null && cards.size() > 0) {
                    db.execNonQuery("update card_info set delete_tag=1");
                }
            } else {
                if (cards == null || cards.size() == 0) {
                    //本地没有卡信息，全部保存
                    for (int j = 0; j < cardInfos.size(); j++) {
                        db.save(cardInfos.get(j));
                    }
                } else {
                    int index = 0;
                    //比较卡库
                    for (CardInfo cardInfo : cardInfos) {
                        boolean exsit = false;
                        for (CardInfo mCardInfo : cards) {
                            if (mCardInfo.getCardNum().equals(cardInfo.getCardNum())) {
                                cardInfo.setId(mCardInfo.getId());
                                exsit = true;
                                break;
                            }
                        }
                        if (exsit) {
                            //存在相同卡，更新信息
                            cardInfo.setDeleteTag(0);
                            db.saveOrUpdate(cardInfo);
                        } else {
                            db.save(cardInfo);
                        }
                    }
                    for (CardInfo mCardInfo : cards) {
                        boolean exsit = false;
                        for (CardInfo cardInfo : cardInfos) {
                            if (mCardInfo.getCardNum().equals(cardInfo.getCardNum())) {
                                exsit = true;
                                break;
                            }
                        }
                        if (!exsit) {
                            //本地的卡号被删除
                            db.execNonQuery("update card_info set  delete_tag=1 where id=" + mCardInfo.getId());
                        }
                        index++;
                    }
                }
            }
            return true;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

}
